const WXAPI = require('apifm-wxapi')
const CONFIG = require('../../config.js')
const SETGOODS = require('../../utils/setgoos.js')
//获取应用实例
var app = getApp()
Page({
  data: {
    inputShowed: false, // 是否显示搜索框
    inputVal: "", // 搜索框内容
    category_box_width: 750, //分类总宽度
    loadingHidden: false, // loading
    userInfo: {},
    selectCurrent: 0,
    categories: [],
    activeCategoryId: 0,
    goods: [],
    
    scrollTop: 0,
    loadingMoreHidden: true,

    coupons: [],

    curPage: 1,
    pageSize: 10,
    cateScrollTop: 0,
    shops:[],
    shopListShow:false,//更多商铺
    promptText:'',//公告
    shopInfo:'',
    radio: '1'
  },
  toSearchPage(){
    wx.navigateTo({
      url: '/pages/search/search?type=searchGoods',
    })
  },
  showShopInfoFun(shopno) {
    let that = this;
    let shopNo = (shopno && shopno != '') ? shopno : app.globalData.shopNo; 
    if (shopNo && shopNo != '') {
      WXAPI.getShopAddress(shopNo).then(function (res) {
        if (res.retCode === '200') {
          that.setData({
            shopInfo: res.data,
          })
          wx.setStorage({
            key: 'shopNo',
            data: res.data.shopNo,
          })
        } else {
          wx.showModal({
            title: '错误',
            content: res.retMsg,
            showCancel: false
          })
        }
      })
    } else {
      setTimeout(function () {
        that.showShopInfoFun(shopno);
      }, 300)
    }
  },
  showMoreShops(){
    this.setData({
      shopListShow:true,
    })
  },
  closeCover(){
    this.setData({
      shopListShow: false,
    })
  },

  tabClick: function(e) {
    let offset = e.currentTarget.offsetLeft;
    if (offset > 150) {
      offset = offset - 150
    } else {
      offset = 0;
    }
    this.setData({
      activeCategoryId: e.currentTarget.id,
      curPage: 1,
      cateScrollTop: offset,
      goods: [],
    });
    if (this.data.activeCategoryId == 0) {
      this.setData({
        loadingMoreHidden:true,
      })
      this.seachGoodsList();
    }else{
      this.setData({
        loadingMoreHidden: false,
      })
      this.getShowItemByCatNo(this.data.activeCategoryId);
    }
    
    // this.getGoodsList(this.data.activeCategoryId);
  },
  toDetailsTap: function(e) {
    // console.log(e.currentTarget.dataset.id)
    wx.navigateTo({
      url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
    })
  },
  tapBanner: function(e) {
    if (e.currentTarget.dataset.id != 0) {
      wx.navigateTo({
        url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
      })
    }
  },
  bindTypeTap: function(e) {
    this.setData({
      selectCurrent: e.index
    })
  },
  onLoad: function(e) {   
    wx.showShareMenu({
      withShareTicket: true
    }) 
    const that = this;
    // if (e && e.query && e.query.inviter_id) { 
    //   wx.setStorageSync('referrer', e.query.inviter_id)
    // }
    console.log(JSON.stringify(e))
    if (e && e.scene) {
      const scene = decodeURIComponent(e.scene)
      if (scene) {  
        console.log('scene', e)      
        // wx.setStorageSync('referrer', scene.substring(11))
        app.globalData.shopNo = scene;
        app.setShopNo(scene);
        that.goodsCategory(scene);
      }
    }else if (e && e.shopNo){
      app.globalData.shopNo = e.shopNo;
      app.setShopNo(e.shopNo);
      that.goodsCategory(e.shopNo);
    }else{
      app.setShopNo();
      that.goodsCategory('');
    }
    wx.setNavigationBarTitle({
      title: '店铺'
    })
    
    // that.getRandomItem()
    that.getNotice()
    // that.kanjiaGoods()
    // that.pingtuanGoods()
    
  },
  onShow(){
    app.getGoodsNo();
  },
  goodsCategory(shopno){
    let that = this;
    let shopNo = (shopno && shopno != '') ? shopno : app.globalData.shopNo; 
    if (shopNo && shopNo != '') {
      WXAPI.goodsCategory(shopNo).then(function (res) {
        let categories = [{
          catNo: 0,
          icon: '/images/fl.png',
          catName: "全部"
        }];
        // let categories = [];
        if (res.retCode == 200) {
          categories = categories.concat(res.data)
        }
        // const _n = Math.ceil(categories.length / 2)
        const _n = categories.length;
        that.setData({
          categories: categories,
          category_box_width: 170 * _n,
          activeCategoryId: 0,
          curPage: 1,
          goods: [],
        });
        // console.log(that.data.categories)
        that.seachGoodsList('');
        // that.getRecentShop();
        that.showShopInfoFun();
      })
    } else {
      setTimeout(function () {
        that.goodsCategory(shopno);
      }, 300)
    }

    
  },
  onPageScroll(e) {
    // let scrollTop = this.data.scrollTop
    // console.log(e.scrollTop)
    this.setData({
      scrollTop: e.scrollTop
    })
  },
  // getRandomItem(){
  //   const that = this;
  //   WXAPI.randomItem().then(function(res) {
  //     if (res.retCode === '200'){
  //       console.log(res.data)
  //       that.setData({
  //         goodsRecommend: res.data
  //       })
  //     }
  //   })
  // },
  // getGoodsList: function(categoryId, append) {
  //   if (categoryId == 0) {
  //     categoryId = "";
  //   }
  //   var that = this;
  //   wx.showLoading({
  //     "mask": true
  //   })
  //   WXAPI.randomItem().then(function(res) {
  //     wx.hideLoading()
  //     if (!res.retCode||res.retCode!=200) {
  //       let newData = {
  //         loadingMoreHidden: false
  //       }
  //       // if (!append) {
  //       //   newData.goods = []
  //       // }
  //       that.setData(newData);
  //       return
  //     }
  //     let goods = [];
  //     // if (append) {
  //     //   goods = that.data.goods
  //     // }
  //     for (var i = 0; i < res.data.length; i++) {
  //       goods.push(res.data[i]);
  //     }
  //     that.setData({
  //       loadingMoreHidden: true,
  //       goods: goods,
  //     });
  //   })
  // },


  getShowItemByCatNo(no) {
    var that = this;
    wx.showLoading({
      "mask": true
    })
    
    WXAPI.getGoodsByCat(no).then(function (res) {
      wx.hideLoading()
      if (res.retCode !== '200') {
        let newData = {
          loadingMoreHidden: false
        }
        that.setData(newData);
        return
      }
      let goods = [];
      // if (no) {
      //   goods = that.data.goods
      // }
      for (var i = 0; i < res.data.length; i++) {
        goods.push(res.data[i]);
      }
      that.setData({
        // loadingMoreHidden: true,
        goods: goods,
      });
    })
  },

  // getFindChildItemCatByNo(no){
  //   var that = this;
  //   wx.showLoading({
  //     "mask": true
  //   })
  //   WXAPI.goodsCatItem({
  //     catNo: no,
  //   }).then(function (res) {
  //     wx.hideLoading()
  //     if (res.retCode !== '200') {
  //       let newData = {
  //         loadingMoreHidden: false
  //       }
  //       that.setData(newData);
  //       return
  //     }
  //     let goods = [];
  //     if (append) {
  //       goods = that.data.goods
  //     }
  //     for (var i = 0; i < res.data.list.length; i++) {
  //       goods.push(res.data.list[i]);
  //     }
  //     that.setData({
  //       loadingMoreHidden: true,
  //       goods: goods,
  //     });
  //   })
  // },
  seachGoodsList: function (append) {
    var that = this;
    wx.showLoading({
      "mask": true
    })
    WXAPI.goods({
      //categoryId: categoryId,
      // keyWords: that.data.inputVal,
      keyWords: '',
      pageNum: this.data.curPage,
      pageSize: this.data.pageSize
    }).then(function (res) {
      wx.hideLoading()
      if (res.retCode !== '200') {
        let newData = {
          loadingMoreHidden: false
        }
        that.setData(newData);
        return
      }
      let goods = that.data.goods;
      for (var i = 0; i < res.data.list.length; i++) {
        goods.push(res.data.list[i]);
      }
      that.setData({
        loadingMoreHidden: true,
        goods: goods,
      });
    })
  },
  // getCoupons: function() {
  //   var that = this;
  //   WXAPI.coupons().then(function (res) {
  //     if (res.code == 0) {
  //       that.setData({
  //         coupons: res.data
  //       });
  //     }
  //   })
  // },
  onShareAppMessage: function() {
    let that = this;  
    return {
      title: that.data.shops[0].shopName,
      path: '/pages/index/index?shopNo=' + wx.getStorageSync('shopNo')
    }
  },
  // 获取某个店铺的最新公告
  getNotice: function(shopno) {
    var that = this;
    let shopNo = (shopno && shopno != '') ? shopno : app.globalData.shopNo; 
    if (shopNo && shopNo != '') {
      WXAPI.noticeList({'shopNo': shopNo}).then(function (res) {
        if (res.retCode === '200') {
          that.setData({
            promptText: res.data.noticeContent
          });
        }
      })
    } else {
      setTimeout(function () {
        that.getNotice(shopno)
      }, 300)
    }
    
  },
  toShopCar(e){
    let that = this;
    let itemNo = e.currentTarget.dataset.itemno;
    for(let item of that.data.goods){
      // console.log(item)
      if (item.itemNo == itemNo){
        item.buyNumber = 1;
        for (let [index ,dots] of item.itemSkuResultDtos.entries()){
          dots.checked = false;
          dots.value = index;
          dots.text = dots.stockTitle;
        }
        // 选中的规格
        item.itemSkuResultDtos[0].checked = true;
        item.value = 0;
        item.price = item.itemSkuResultDtos[0].price;
        // 购物车选中标识
        item.checked = false; 
        item.buyMoney = parseFloat(item.price) * (item.buyNumber); 
        item.stockNo = item.itemSkuResultDtos[0].stockNo; 
        item.stockTitle = item.itemSkuResultDtos[0].stockTitle;
        item.narrowPicUrl = item.itemSkuResultDtos[0].narrowPicUrl;
        // wx.setStorage({
        //   key: 'shopCarInfo',
        //   data: item
        // })


        SETGOODS.setGoods(item, itemNo, item.itemSkuResultDtos[0].stockNo, item.shopNo);

        // wx.getStorage({
        //   key: 'shopCarInfo',
        //   success: function (res) {
        //     let resArr = res.data;
        //     resArr.push(item)
        //     wx.setStorage({
        //       key: 'shopCarInfo',
        //       data: resArr
        //     })
        //   },
        //   fail(){
        //     let resArr = [];
        //     resArr.push(item)
        //     wx.setStorage({
        //       key: 'shopCarInfo',
        //       data: resArr
        //     })
        //   }
        // })
      }
    }
    wx.showToast({
      title: '商品已添加购物车',
      duration: 1500,
    });
  },
  // toSearch: function() {
  //   this.setData({
  //     curPage: 1,
  //     goods:[]
  //   });
  //   //this.getGoodsList(this.data.activeCategoryId);
  //   this.seachGoodsList(this.data.inputVal);
  // },
  onReachBottom: function() {
    this.setData({
      curPage: this.data.curPage + 1
    });
    
    if (this.data.activeCategoryId == 0) {
      this.seachGoodsList(this.data.activeCategoryId, true)
    } else {
      this.getShowItemByCatNo(this.data.activeCategoryId);
    }
  },
  onPullDownRefresh: function() {
    this.setData({
      curPage: 1,
      goods:[],
    });
    // this.seachGoodsList(this.data.activeCategoryId)
    if (this.data.activeCategoryId == 0){
      this.seachGoodsList(this.data.activeCategoryId)
    }else{
      this.getShowItemByCatNo(this.data.activeCategoryId);
    }
    wx.stopPullDownRefresh()
  },
  // onPageScroll(e){
  //   console.log(e)
  //   if (e.scrollTop > 100){
  //     this.set
  //   }
  // },
  // 以下为搜索框事件
  // showInput: function () {
  //   this.setData({
  //     inputShowed: true
  //   });
  // },
  // hideInput: function () {
  //   this.setData({
  //     inputVal: "",
  //     inputShowed: false
  //   });
  // },
  // clearInput: function () {
  //   this.setData({
  //     inputVal: ""
  //   });
  // },
  // inputTyping: function (e) {
  //   this.setData({
  //     inputVal: e.detail.value
  //   });
  // },
  // 获取砍价商品
  // async kanjiaGoods(){
  //   const res = await WXAPI.goods({
  //     kanjia: true
  //   });
  //   if (res.code == 0) {
  //     this.setData({
  //       kanjiaList: res.data
  //     })
  //   }
  // },
  // goCoupons: function (e) {
  //   wx.navigateTo({
  //     url: "/pages/coupons/index"
  //   })
  // },
  // pingtuanGoods(){ // 获取团购商品列表
  //   const _this = this
  //   WXAPI.goods({
  //     pingtuan: true
  //   }).then(res => {
  //     if (res.code === 0) {
  //       _this.setData({
  //         pingtuanList: res.data
  //       })
  //     }
  //   })
  // }
})